<template>
  <div class="admin-layout">
    <!-- 左侧导航菜单 -->
    <div class="sidebar" :class="{ collapsed: isCollapsed }">
      <div class="logo">
        <h2 v-if="!isCollapsed">COKFOOD</h2>
        <h2 v-else>CF</h2>
      </div>
      <div class="menu">
        <div v-for="item in menuItems" :key="item.path" class="menu-item" :class="{
          active: isActive(item),
          'has-children': item.children && item.children.length,
        }">
          <div class="menu-item-title" @click="
            item.children && item.children.length ? toggleSubmenu(item) : navigateTo(item.path)
            ">
            <i :class="['icon', `fa-${item.icon}`]"></i>
            <span v-if="!isCollapsed">{{ item.title }}</span>
            <i v-if="!isCollapsed && item.children && item.children.length" :class="[
              'submenu-arrow',
              openedMenus.includes(item.path) ? 'fa-angle-down' : 'fa-angle-right',
            ]"></i>
          </div>

          <div v-if="!isCollapsed && item.children && item.children.length" class="submenu"
            v-show="openedMenus.includes(item.path)">
            <div v-for="subItem in item.children" :key="subItem.path" class="submenu-item"
              :class="{ active: isActive(subItem) }" @click="navigateTo(subItem.path)">
              <i v-if="subItem.icon" :class="['icon', `fa-${subItem.icon}`]"></i>
              <span>{{ subItem.title }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="collapse-button" @click="toggleCollapse">
        <i :class="['icon', isCollapsed ? 'fa-angle-right' : 'fa-angle-left']"></i>
      </div>
    </div>

    <!-- 右侧内容区域 -->
    <div class="main-content">
      <!-- 顶部标题栏 -->
      <div class="header">
        <div class="breadcrumb">
          <span v-for="(item, index) in breadcrumbs" :key="index">
            <span class="breadcrumb-item" :class="{ clickable: index < breadcrumbs.length - 1 }"
              @click="index < breadcrumbs.length - 1 ? navigateTo(item.path) : null">
              {{ item.title }}
            </span>
            <span v-if="index < breadcrumbs.length - 1" class="breadcrumb-separator">/</span>
          </span>
        </div>
        <div class="user-info">
          <div class="dropdown">
            <span class="username" @click="toggleUserDropdown">管理员 <i class="icon fa-angle-down"></i></span>
            <div class="dropdown-menu" v-show="isUserDropdownOpen">
              <div class="dropdown-item" @click="viewProfile">
                <i class="icon fa-user"></i> 个人信息
              </div>
              <div class="dropdown-item" @click="viewSettings">
                <i class="icon fa-cog"></i> 系统设置
              </div>
              <div class="dropdown-divider"></div>
              <div class="dropdown-item" @click="logout">
                <i class="icon fa-sign-out-alt"></i> 退出登录
              </div>
            </div>
          </div>
          <div class="avatar">
            <img src="https://via.placeholder.com/40" alt="用户头像" />
          </div>
        </div>
      </div>

      <!-- 内容区域 -->
      <div class="content">
        <router-view v-slot="{ Component }">
          <transition name="fade" mode="out-in">
            <keep-alive>
              <component :is="Component" />
            </keep-alive>
          </transition>
        </router-view>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

// 菜单折叠状态
const isCollapsed = ref(false)

// 打开的子菜单状态
const openedMenus = ref([])

// 用户下拉菜单状态
const isUserDropdownOpen = ref(false)

// 当前激活路径
const currentPath = computed(() => route.path)

// 生成面包屑
const breadcrumbs = computed(() => {
  const result = [{ title: '首页', path: '/admin' }]
  const matched = route.matched

  if (matched.length) {
    for (let i = 1; i < matched.length; i++) {
      const item = matched[i]
      if (item.meta && item.meta.title) {
        const parts = item.meta.title.split('-')
        const title = parts.length > 1 ? parts[1].trim() : parts[0].trim()
        result.push({
          title,
          path: item.path,
        })
      }
    }
  }

  return result
})

// 判断菜单项是否激活
const isActive = (item) => {
  if (item.path === currentPath.value) return true
  if (item.children) {
    return item.children.some((child) => child.path === currentPath.value)
  }
  return false
}

// 扩展的菜单项配置，添加子菜单支持
const menuItems = [
  {
    title: '控制台',
    path: '/admin/dashboard',
    icon: 'tachometer-alt',
  },
  {
    title: '商户管理',
    path: '/admin/merchants',
    icon: 'store',
  },
  {
    title: '产品管理',
    path: '/admin/products',
    icon: 'shopping-bag',
  },
  {
    title: '用户管理',
    path: '/admin/users',
    icon: 'users',
  },
  {
    title: '订单管理',
    path: '/admin/orders',
    icon: 'shopping-cart',
  },
  {
    title: '财务管理',
    path: '/admin/finance',
    icon: 'wallet',
    children: [
      {
        title: '提现审核',
        path: '/admin/finance/withdrawals',
        icon: 'money-check-alt',
      },
      {
        title: '提现手续费',
        path: '/admin/withdrawalFees',
        icon: 'exchange-alt',
      },
    ],
  },
  {
    title: 'Banner管理',
    path: '/admin/banner',
    icon: 'shopping-cart',
  },
  {
    title: '粉丝管理',
    path: '/admin/fans',
    icon: 'shopping-cart',
  },
]

// 切换菜单折叠状态
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
  // 可以将折叠状态保存到本地存储中，以便页面刷新后保持状态
  localStorage.setItem('adminMenuCollapsed', isCollapsed.value)
}

// 切换子菜单展开状态
const toggleSubmenu = (item) => {
  const index = openedMenus.value.indexOf(item.path)
  if (index > -1) {
    openedMenus.value.splice(index, 1)
  } else {
    openedMenus.value.push(item.path)
  }
  // 保存展开的子菜单状态
  localStorage.setItem('adminOpenedMenus', JSON.stringify(openedMenus.value))
}

// 导航到指定路径
const navigateTo = (path) => {
  router.push(path)
}

// 切换用户下拉菜单
const toggleUserDropdown = () => {
  isUserDropdownOpen.value = !isUserDropdownOpen.value
}

// 查看个人信息
const viewProfile = () => {
  // TODO: 实现查看个人信息功能
  console.log('查看个人信息')
  isUserDropdownOpen.value = false
}

// 查看系统设置
const viewSettings = () => {
  router.push('/admin/system')
  isUserDropdownOpen.value = false
}

// 退出登录
const logout = () => {
  // TODO: 实现退出登录功能
  console.log('退出登录')
  isUserDropdownOpen.value = false
  router.push('/auth/login')
}

// 监听路由变化，自动展开对应子菜单
watch(
  () => route.path,
  (newPath) => {
    for (const item of menuItems) {
      if (item.children && item.children.some((child) => child.path === newPath)) {
        if (!openedMenus.value.includes(item.path)) {
          openedMenus.value.push(item.path)
          localStorage.setItem('adminOpenedMenus', JSON.stringify(openedMenus.value))
        }
      }
    }

    // 点击其他地方关闭用户下拉菜单
    isUserDropdownOpen.value = false
  },
)

// 组件挂载时，从本地存储中获取菜单折叠状态
onMounted(() => {
  // 恢复菜单折叠状态
  const savedState = localStorage.getItem('adminMenuCollapsed')
  if (savedState !== null) {
    isCollapsed.value = savedState === 'true'
  }

  // 恢复展开的子菜单状态
  const savedOpenedMenus = localStorage.getItem('adminOpenedMenus')
  if (savedOpenedMenus) {
    try {
      openedMenus.value = JSON.parse(savedOpenedMenus)
    } catch (e) {
      console.error('解析保存的子菜单状态失败', e)
    }
  }

  // 根据当前路径自动展开对应子菜单
  for (const item of menuItems) {
    if (item.children && item.children.some((child) => child.path === route.path)) {
      if (!openedMenus.value.includes(item.path)) {
        openedMenus.value.push(item.path)
      }
    }
  }

  // 添加全局点击事件监听，点击外部关闭用户下拉菜单
  document.addEventListener('click', (e) => {
    if (isUserDropdownOpen.value) {
      const dropdown = document.querySelector('.dropdown')
      if (dropdown && !dropdown.contains(e.target)) {
        isUserDropdownOpen.value = false
      }
    }
  })
})
</script>

<style scoped>
.admin-layout {
  display: flex;
  height: 100vh;
  width: 100%;
  overflow: hidden;
}

/* 侧边栏样式 */
.sidebar {
  width: 240px;
  background-color: #2c3e50;
  color: #ecf0f1;
  transition: all 0.3s;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.sidebar.collapsed {
  width: 64px;
}

.logo {
  padding: 20px;
  text-align: center;
  border-bottom: 1px solid #34495e;
}

.logo h2 {
  margin: 0;
  font-size: 1.5rem;
  white-space: nowrap;
}

.menu {
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
}

.menu-item {
  margin-bottom: 2px;
  transition: all 0.3s;
  white-space: nowrap;
}

.menu-item-title {
  padding: 12px 20px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
}

.menu-item-title:hover {
  background-color: #34495e;
}

.menu-item.active>.menu-item-title {
  background-color: #e74c3c;
  color: white;
}

.menu-item .icon {
  margin-right: 10px;
  width: 20px;
  text-align: center;
}

.submenu-arrow {
  margin-left: auto;
  transition: transform 0.3s;
}

.submenu {
  overflow: hidden;
  background-color: #34495e;
}

.submenu-item {
  padding: 10px 20px 10px 50px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s;
}

.submenu-item:hover {
  background-color: #435c74;
}

.submenu-item.active {
  background-color: #e74c3c;
  color: white;
}

.submenu-item .icon {
  margin-right: 10px;
  width: 16px;
  text-align: center;
}

.collapse-button {
  padding: 15px 20px;
  text-align: center;
  cursor: pointer;
  border-top: 1px solid #34495e;
}

.collapse-button:hover {
  background-color: #34495e;
}

/* 主内容区域样式 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #f5f6fa;
}

.header {
  height: 64px;
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 1;
}

.breadcrumb {
  font-size: 16px;
  color: #34495e;
}

.breadcrumb-item.clickable {
  cursor: pointer;
  color: #2980b9;
}

.breadcrumb-item.clickable:hover {
  text-decoration: underline;
}

.breadcrumb-separator {
  margin: 0 8px;
  color: #bdc3c7;
}

.user-info {
  display: flex;
  align-items: center;
}

.username {
  margin-right: 10px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.username .icon {
  margin-left: 4px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.dropdown {
  position: relative;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: 10px;
  min-width: 160px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.dropdown-item {
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
}

.dropdown-item:hover {
  background-color: #f8f9fa;
}

.dropdown-item .icon {
  margin-right: 8px;
  width: 16px;
}

.dropdown-divider {
  height: 1px;
  background-color: #e9ecef;
  margin: 4px 0;
}

.content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    z-index: 2;
    height: 100vh;
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
    transform: translateX(0);
  }

  .sidebar.collapsed {
    transform: translateX(-240px);
  }

  .main-content {
    margin-left: 0;
  }
}

/* 页面过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
